# -*- coding: utf-8 -*-

from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from sqlmodel import SQLModel, create_engine, Session
from pathlib import Path
import logging
from typing import Generator
import os

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

# 数据库配置
BASE_DIR = Path(__file__).parent
SQL_DIR = BASE_DIR / "sql"
SQL_DIR.mkdir(exist_ok=True)
DATABASE_URL = "sqlite:///{}/sqlite.db".format(SQL_DIR)

# 创建数据库引擎
engine = create_engine(
    url=DATABASE_URL,
    echo=False,
    connect_args={"check_same_thread": False}
)

# 依赖项：获取数据库会话
def get_db() -> Generator[Session, None, None]:
    """获取数据库会话连接"""
    with Session(bind=engine) as session:
        yield session

# 创建数据库表
def create_db_and_tables():
    try:
        SQLModel.metadata.create_all(engine)
        logger.info("数据库表创建成功")
    except Exception as e:
        logger.error("数据库表创建失败: {}".format(e))
        raise e

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动事件
    logger.info("服务启动...")
    create_db_and_tables()
    yield
    # 关闭事件
    logger.info("服务关闭...")

# 创建FastAPI应用
app = FastAPI(
    title="empty_project_fastapi_uniapp API", 
    description="简化版API服务",
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 根路由
@app.get("/")
async def root():
    return {"message": "欢迎使用empty_project_fastapi_uniapp API"}

# 导入并包含路由 - 放在最后避免循环导入
from routes import router
app.include_router(router)

# 启动服务器
if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
    )

